﻿using FileService.Domain;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileService.infrastructure.Services
{
    public class ThumbnailService : IThumbnailService
    {

        private IOptionsSnapshot<SMBStorageOptions> options;
        public ThumbnailService(IOptionsSnapshot<SMBStorageOptions> options)
        {
            this.options = options;
        }

        private readonly HashSet<string> VideoExtensions = new(StringComparer.OrdinalIgnoreCase)
         {
             ".mp4", ".avi", ".mov", ".mkv", ".wmv", ".flv", ".m4v", ".mpg", ".mpeg", ".3gp"
         };

        public string GenerateThumbnail(string videoFileUrl, int type = 1)
        {
            string workingDir = options.Value.WorkingDir;
            string videoPath = Path.Combine(workingDir, videoFileUrl);

            // 检查视频文件是否存在
            if (!File.Exists(videoPath))
            {
                throw new FileNotFoundException("指定的视频文件不存在。", videoPath);
            }

            string thumbnailPath = Path.ChangeExtension(videoPath, "jpg");

            // 根据 type 参数选择分辨率
            string resolution = type switch
            {
                1 => "672x378",
                2 => "554x960",
                _ => throw new ArgumentException("不支持的 type 参数值。", nameof(type)),
            };

            // 构建 FFmpeg 命令行参数
            string arguments = $"-y -ss 3 -i \"{videoPath}\" -vframes 1 -s {resolution} -q:v 2 \"{thumbnailPath}\"";

            // 创建并启动 FFmpeg 进程
            using Process process = new();
            process.StartInfo.FileName = "ffmpeg";
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.Start();

            // 等待进程完成
            process.WaitForExit();

            return thumbnailPath;
        }

        public bool IsVideoFile(string videoFileUrl)
        {
            if (string.IsNullOrEmpty(videoFileUrl))
            {
                return false;
            }

            // 获取文件的扩展名
            string extension = Path.GetExtension(videoFileUrl);

            // 检查扩展名是否在视频文件扩展名列表中
            return VideoExtensions.Contains(extension);
        }
    }
}
